from sqlalchemy.orm import Session
from models.models import LearnUser
from schemas.user import UserCreate

def create_user(db: Session, user: UserCreate):
    existing_email = db.query(LearnUser).filter(LearnUser.email == user.email).first()
    existing_username = db.query(LearnUser).filter(LearnUser.username == user.username).first()
     # 代表用户已存在
    if existing_email:
        return ValueError(1)
    if existing_username:
        return ValueError(2)
     
    db_user = LearnUser(username=user.username, email=user.email, password_hash=user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def get_user(db: Session, user_id: int):
    return db.query(LearnUser).filter(LearnUser.id == user_id).first()

def get_user_by_email(db: Session, email: str):
    return db.query(LearnUser).filter(LearnUser.email == email).first()

def get_all_users(db: Session):
    return db.query(LearnUser).all()

def update_user(db: Session, user_id: int, username: str, email: str):
    user = db.query(LearnUser).filter(LearnUser.id == user_id).first()
    if user:
        user.username = username
        user.email = email
        db.commit()
        db.refresh(user)
        return user
    return None

def change_password(db: Session, user_id: int, old_password: str, new_password: str):
    user = db.query(LearnUser).filter(LearnUser.id == user_id).first()
    if user:
        if user.check_password(old_password):
            user.password_hash = new_password
            db.commit()
            db.refresh(user)
            return user
        else:
            return None

def delete_user(db: Session, user_id: int):
    user = db.query(LearnUser).filter(LearnUser.id == user_id).first()
    if user:
        db.delete(user)
        db.commit()
        return True
    return False
